package com.qiangesoft.oss.strategy;

import com.qiangesoft.oss.config.FileStoreProperties;
import com.qiangesoft.oss.config.StrategyFactory;
import com.qiangesoft.oss.constant.FileStoreTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地策略实现
 *
 * @author qiangesoft
 * @date 2024-05-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Primary
@ConditionalOnProperty(prefix = "oss", name = "type", havingValue = "local")
public class LocalStrategyImpl implements FileStrategy {

    private String prefix;

    public LocalStrategyImpl(FileStoreProperties fileStoreProperties) {
        this.prefix = fileStoreProperties.getPrefix();
    }

    @Override
    public boolean existsCatalog(String catalog) throws Exception {
        File file = new File(prefix + SLASH + catalog);
        return file.exists();
    }

    @Override
    public void createCatalog(String catalog) throws Exception {
        File file = new File(prefix + SLASH + catalog);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @Override
    public List<String> listCatalogs() throws Exception {
        File file = new File(prefix);
        File[] files = file.listFiles();
        List<String> list = new ArrayList<>();
        for (File subFile : files) {
            if (subFile.isDirectory()) {
                list.add(subFile.getName());
            }
        }
        return list;
    }

    @Override
    public void removeCatalog(String catalog) throws Exception {
        File file = new File(prefix + SLASH + catalog);
        if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public String uploadFile(String catalog, MultipartFile file) throws Exception {
        return null;
    }

    @Override
    public void removeFile(String catalog, String fileName) throws Exception {

    }

    @Override
    public void removeFiles(String catalog, List<String> fileNames) throws Exception {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        StrategyFactory.register(FileStoreTypeEnum.LOCAL, this);
    }
}